package org.ztr.yanai.ai.service.impl;

import jakarta.annotation.Resource;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.messages.SystemMessage;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.stereotype.Service;
import org.ztr.yanai.ai.service.PromptService;
import reactor.core.publisher.Flux;

/**
 * @Author: ZhaoTR
 * @Date: Created in 2025/10/30 20:54
 * @Description: PromptService
 * @Version: 1.0
 */
@Service
public class PromptServiceImpl implements PromptService {

    @Resource(name = "deepseek")
    private ChatModel deepseekChatModel;

    @Resource(name = "qwen")
    private ChatModel qwenChatModel;

    @Resource(name = "deepseekChatClient")
    private ChatClient deepseekChatClient;

    @Resource(name = "qwenChatClient")
    private ChatClient qwenChatClient;

    // === 聊天流式响应（字符串流）===
    public Flux<String> chatAsLegalAssistant(String question) {
        return deepseekChatClient.prompt()
                .system("你是一个法律助手，只回答法律问题，其它问题回复：我只能回答法律相关问题，其它无可奉告")
                .user(question)
                .stream()
                .content();
    }

    // === 聊天流式响应（完整 ChatResponse）===
    public Flux<ChatResponse> chatAsStoryTellerWithResponse(String question) {
        SystemMessage systemMessage = new SystemMessage("你是一个讲故事的助手，每个故事控制在300字以内");
        UserMessage userMessage = new UserMessage(question);
        Prompt prompt = new Prompt(userMessage, systemMessage);
        return deepseekChatModel.stream(prompt);
    }

    // === 聊天流式响应（提取文本）===
    public Flux<String> chatAsHtmlStoryTeller(String question) {
        SystemMessage systemMessage = new SystemMessage("你是一个讲故事的助手，每个故事控制在600字以内且以HTML格式返回");
        UserMessage userMessage = new UserMessage(question);
        Prompt prompt = new Prompt(userMessage, systemMessage);
        return deepseekChatModel.stream(prompt)
                .map(response -> response.getResults().get(0).getOutput().getText());
    }

    // === 非流式单次响应 ===
    public String chatOnce(String question) {
        return deepseekChatClient.prompt()
                .user(question)
                .call()
                .content();
    }

    // === 带工具响应模拟 ===
    public String chatWithWeatherTool(String city) {
        String answer = deepseekChatClient.prompt()
                .user(city + "未来3天天气情况如何?")
                .call()
                .content();

        // 模拟工具调用结果（实际项目中这里应调用真实天气 API）
        String toolResponse = "[工具调用: 查询天气, 参数: " + city + "]";

        return answer + "\n" + toolResponse;
    }
}
